﻿using System;
using Office = Microsoft.Office.Interop;
using System.Reflection;
using System.IO;

namespace Ucto.ToExcelConvertor
{
	public class Presenter
	{
		private static readonly string DefaultInputFileName = "stext.txt";
		private static readonly string DefaultOutputFileName = "stext";

		public Presenter(IView view, string[] args)
		{
			View = view;
			Arguments = args;
		}

		protected string[] Arguments { get; private set; }

		protected IView View { get; private set; }

		protected string InputFileName
		{
			get
			{
				if (Arguments != null && Arguments.Length > 0)
				{
					return Arguments[0];
				}
				else
				{
					return DefaultInputFileName;
				}
			}
		}

		protected string OutputFileName
		{
			get
			{
				string directory = Directory.GetCurrentDirectory();
				string file = null;
				if (Arguments != null && Arguments.Length > 1)
				{
					file = Arguments[1];
				}
				else
				{
					file = DefaultOutputFileName;
				}
				return Path.Combine(directory, file);
			}
		}

		protected Office.Excel.Application Application { get; private set; }

		private Office.Excel._Worksheet OpenExcelWithSheet()
		{
			Application = new Office.Excel.Application();
			Application.Visible = true;

			var workbook = (Office.Excel._Workbook)(Application.Workbooks.Add(Missing.Value));
			return (Office.Excel._Worksheet)workbook.ActiveSheet;
		}

		private void CloseExcel()
		{
			if (Application != null)
			{
				View.DisplayMessage("Ukladam subor {0}", OutputFileName);
				try
				{
					Application.DisplayAlerts = false;
					Application.ActiveWorkbook.SaveAs(Filename: OutputFileName);
				}
				catch (Exception ex)
				{
					View.DisplayError("Chyba pri ukladani excelu do suboru " + OutputFileName, ex);
				}
				finally
				{
					Application.Quit();
				}
			}
		}

		public void Execute()
		{
			View.DisplayHeader(InputFileName);
			
			var startDate = DateTime.UtcNow;

			try
			{
				// open file
				using (var dataReader = DataReader.Open(InputFileName))
				{
					// open excel
					var sheet = OpenExcelWithSheet();
					var excelSheet = new ExcelSheet(sheet);

					// read header
					var header = dataReader.GetHeader();

					// init handler and configure with data from header
					var valueHandler = new ValueToExcelHandler(header.ColumnCount, excelSheet);
					var dataProcessor = new DataProcessor(dataReader, valueHandler);

					// map input data to excel cells
					dataProcessor.Process();
				}
			}
			catch (Exception ex)
			{
				View.DisplayError("Pri vykonavani programu sa vyskytla chyba.", ex);
				return;
			}
			finally
			{
				// save & close application
				CloseExcel();
			}
			
			var endDate = DateTime.UtcNow;
			var duration = endDate - startDate;

			View.DisplayFooter(duration.TotalSeconds);
		}
	}
}
